/*
 * Copyright 2025 arisgo@163.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.arisgo.cloud.flux.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;

/**
 * @author Arisgo
 * @since 2024/6/11
 */
public class ExchangeUtil {

    private static final Logger logger = LoggerFactory.getLogger(ExchangeUtil.class);
    private static final ObjectMapper MAPPER = new ObjectMapper();

    public static Mono<Void> sendResponseError(ServerWebExchange exchange, HttpStatus status) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        response.getHeaders().setAcceptCharset(Lists.newArrayList(StandardCharsets.UTF_8));
        response.setStatusCode(status);

        try {
            response.bufferFactory().wrap(MAPPER.writeValueAsBytes(buildResponseBody(exchange.getRequest().getURI().getPath(), status)));
        } catch (JsonProcessingException e) {
            logger.warn(e.getMessage(), e);
        }
        return response.setComplete();
    }

    public static Map<String, Object> buildResponseBody(String path, HttpStatus status) {
        return buildResponseBody(path, status.value(), status.getReasonPhrase());
    }

    public static Map<String, Object> buildResponseBody(Object path, Object status, Object msg) {
        Map<String, Object> result = Maps.newLinkedHashMap();
        result.put("code", status);
        result.put("msg", msg);
        result.put("path", path);
        result.put("timestamp", new Date());
        return result;
    }

}
